package com.sdry.web.controller.llm;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.llm.ExceptionLog;
import com.sdry.service.llm.ExceptionLogService;
import com.sdry.utils.IPUtils;


/** 
* 全局拦截异常，存入数据库中
* @author lian 
* @version 1.0
* @time 2018年10月23日 下午10:11:04
* 有IP, 发生异常的类名，方法名，异常类型，发生时间， 异常信息
*/
public class GetExceptionLog implements HandlerExceptionResolver {

	private static final Logger LOGGER = LoggerFactory.getLogger(GetExceptionLog.class);

	@Resource
	private ExceptionLogService exlogService;   //注入异常日志的service
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("ex", ex);
		if (handler instanceof HandlerMethod) {
			LOGGER.info(">>>>>>系统异常，记录异常信息到数据库------start------");
			LOGGER.info(ex.getMessage());
			// 远程访问IP
			String ip = IPUtils.getRemortIP(request);
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			String className = handlerMethod.getBeanType().getName();
			String methodName = handlerMethod.getMethod().getName();
			StringWriter sw = new StringWriter();
			ex.printStackTrace(new PrintWriter(sw, true));
 
			// 插入异常日志到数据库
			ExceptionLog log = new ExceptionLog();
			log.setIp(ip);
			log.setClassName(className);
			log.setMethodName(methodName);
			log.setExceptionType(ex.getClass().getSimpleName());
			log.setExceptionMsg(ex.getMessage()); // 异常详细信息
			Date date = new Date();
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String stringDate = sdf.format(date);
			log.setAddtime(stringDate);
			exlogService.insertExceptionLogSelective(log);
			LOGGER.info(">>>>>>系统异常，记录异常信息到数据库------end------");
 
		}
      
		return null;
	}
}
